package cc.vicp.djx314.starfood.service.order.impls;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import cc.vicp.djx314.starfood.dao.dish.DishMapper;
import cc.vicp.djx314.starfood.dao.order.OrderMapper;
import cc.vicp.djx314.starfood.domain.account.Personnel;
import cc.vicp.djx314.starfood.domain.account.User;
import cc.vicp.djx314.starfood.domain.dish.Dish;
import cc.vicp.djx314.starfood.domain.order.Order;
import cc.vicp.djx314.starfood.domain.order.OrderDish;
import cc.vicp.djx314.starfood.service.exception.DishNotFoundException;
import cc.vicp.djx314.starfood.service.exception.NoOrderDishesException;
import cc.vicp.djx314.starfood.service.exception.OrderNotFoundException;
import cc.vicp.djx314.starfood.service.order.CartService;
import cc.vicp.djx314.starfood.service.order.CurrentOrder;
import cc.vicp.djx314.starfood.service.order.OrderService;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	OrderMapper orderMapper;

	@Autowired
	CartService cartService;

	@Autowired
	CurrentOrder currentOrder;

	@Autowired
	DishMapper dishMapper;

	public static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Override
	@Transactional(readOnly = false)
	public boolean createOrder(Order order) throws NoOrderDishesException {
		if (order.getOrderDishes() == null || order.getOrderDishes().size() == 0) {
			throw new NoOrderDishesException("该订单没有包含菜式");
		}
		Date date = new Date();
		order.setTime(date);
		orderMapper.createOrder(order);
		for (OrderDish orderDish : order.getOrderDishes()) {
			orderMapper.createOrderDish(orderDish, order.getId());
		}
		orderMapper.updateOrderBySum(order.getId());
		return true;
	}

	@Override
	@Transactional(readOnly = true)
	public List<OrderDish> getMoreOrderDishesInfo(List<OrderDish> orderDishes) throws DishNotFoundException {
		List<OrderDish> myOrderDishes = null;
		if (orderDishes != null) {
			for (OrderDish orderDish : orderDishes) {
				Dish dish = cartService.findDishForCart(orderDish.getDish().getId());
				orderDish.setDish(dish);
			}
			myOrderDishes = orderDishes;
		}
		return myOrderDishes;
	}

	@Override
	@Transactional(readOnly = true)
	public Order getOrderForPersonnel(Integer orderId) throws OrderNotFoundException {
		Order order = orderMapper.getOrderForPersonnel(orderId);
		if (order == null) {
			throw new OrderNotFoundException("order的Id为" + orderId + "的订单找不到");
		}
		return order;
	}

	@Override
	@Transactional(readOnly = true)
	public Order getCurrentOrderForPersonnel() throws OrderNotFoundException {
		List<Integer> alreadyDealIds = currentOrder.getCurrentOrder();
		List<Order> orders = orderMapper.getCurrentOrderForPersonnel(alreadyDealIds);
		if (orders == null || orders.size() == 0) {
			throw new OrderNotFoundException("找不到需要处理的订单");
		}
		Order order = orders.get(0);
		currentOrder.addCurrnetOrder(order.getId());
		return order;
	}

	@Override
	@Transactional(readOnly = false)
	public void updateOrderCancled(Integer orderId) {
		orderMapper.updateOrderCancled(orderId);
	}

	@Override
	@Transactional(readOnly = false)
	public void updateOrderEnabled(Order order) {
		List<OrderDish> orderDishes = order.getOrderDishes();
		for (OrderDish orderDish : orderDishes) {
			Double price = orderMapper.getOrderDishPriceById(orderDish.getId());
			Integer num = orderDish.getNum();
			Double dishSum = price * num;
			orderDish.setDishSum(dishSum);
			orderMapper.updateOrderDishCount(orderDish);
		}
		orderMapper.updateOrderBySum(order.getId());
		orderMapper.updateOrderEnabled(order.getId());
		orderMapper.updateOrderInfo(order);
	}

	@Override
	@Transactional(readOnly = true)
	public Order getOrderForFlowById(Integer orderId) {
		Order resultOrder = null;
		try {
			resultOrder = orderMapper.getOrderForFlowById(orderId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultOrder;
	}

	@Override
	@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED)
	public void updateOrderFlowStatus(Integer orderId, Integer status) throws Exception {
		int rows = orderMapper.updateOrderFlowStatus(orderId, status);
		if (rows != 1) {
			throw new Exception("更新order状态出现多行被更改,原本是只能更改一行,orderId为" + orderId);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void updateOrderFlowDraw(Integer orderId) throws Exception {
		int rows = orderMapper.updateOrderDraw(orderId);
		if (rows != 1) {
			throw new Exception("抽回订单数量不是1,订单号是" + orderId);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public Order getOrderCancledById(Integer orderId) {
		Order result = null;
		result = orderMapper.getOrderCancledById(orderId);
		return result;
	}

	@Override
	@Transactional(readOnly = false)
	public void updateOrderUncanceled(Integer orderId) throws Exception {
		int rows = - 1;
		rows = orderMapper.updateOrderUncanceled(orderId);
		if (rows != 1) {
			throw new Exception("恢复id为" + orderId + "的订单出现问题,行数不对应");
		}
	}

	@Override
	@Transactional(readOnly = true)
	public List<Order> getCanceledOrderToday() {
		Date date = new Date();
		Calendar todayCal = Calendar.getInstance();
		todayCal.setTime(date);
		todayCal.set(Calendar.HOUR_OF_DAY, 0);
		todayCal.set(Calendar.MINUTE, 0);
		todayCal.set(Calendar.SECOND, 0);
		todayCal.set(Calendar.MILLISECOND, 0);
		Date today = todayCal.getTime();
		List<Order> orders = orderMapper.getCanceledOrderToday(today);
		return orders;
	}

	@Override
	public void updateOrderFlowStatusFinish(Integer orderId, Integer status,
			Personnel personnel) throws Exception {
		int rows = orderMapper.updateOrderFlowStatusFinish(orderId, status, personnel);
		if (rows != 1) {
			throw new Exception("更新最终状态的时候数据库修改的行数不是一行");
		}
		List<OrderDish> orderDishes = dishMapper.findOrderDishByOrder(orderId);
		if (orderDishes != null && orderDishes.size() > 0) {
			for (OrderDish orderDish : orderDishes) {
				java.sql.Date myDate = new java.sql.Date(new Date().getTime());
				int effectRows = dishMapper.updateDishDayBuy(orderDish.getDish().getId(),
						myDate, orderDish.getNum());
				if (effectRows != 1) {
					dishMapper.createDishDayBuy(orderDish.getDish().getId(),
							myDate, orderDish.getNum());
				}
			}
		}
	}

	@Override
	public List<Order> getOrdersInfoForUser(User user) {
		List<Order> orders = orderMapper.getOrdersInfoForUser(user);
		return orders;
	}
}